import React, { Component } from "react";
import {Form,Input,Select,Table,Divider,Button,Modal,DatePicker,Row,Col,Upload} from "antd";
import Content from "../../components/Content/Content";
import {  InputNumber, Popconfirm, } from 'antd';
import moment from "moment";

const { Option } = Select;
const { Item } = Form;
const InputGroup = Input.Group;

const EditableContext = React.createContext();

const EditableRow = ({ form, index, ...props }) => (
  <EditableContext.Provider value={form}>
    <tr {...props} />
  </EditableContext.Provider>
);
const EditableFormRow = Form.create()(EditableRow);

class EditableCell extends React.Component {
  getInput = () => {
    if (this.props.inputType === 'number') {
      return <InputNumber />;
    }
    return <Input />;
  };

  renderCell = ({ getFieldDecorator }) => {
    const {
      editing,
      dataIndex,
      title,
      inputType,
      record,
      index,
      children,
      ...restProps
    } = this.props;
    return (
      <td {...restProps}>
        {editing ? (
          <Form.Item style={{ margin: 0 }}>
            {getFieldDecorator(dataIndex, {
              rules: [
                {
                  required: true,
                  message: `${title}不能为空!`,
                },
              ],
              initialValue: record[dataIndex],
            })(this.getInput())}
          </Form.Item>
        ) : (
          children
        )}
      </td>
    );
  };

  render() {
    return <EditableContext.Consumer>{this.renderCell}</EditableContext.Consumer>;
  }
}

class EditableTable extends React.Component {
  constructor(props) {
    super(props);
    this.columns = [
      {
        title: 'ID',
        dataIndex: 'id',
        editable: false,
        fixed: 'left',
        width:120,
      },      
      {
        title: '筛选菌株编号',
        dataIndex: 'sxjj_id',
        editable: true,
        fixed: 'left',
        width:200,
      },  
      {
        title: '菌株保藏编号',
        dataIndex: 'jzbc_id',
        editable: true,
        fixed: 'left',
        width:200,
      },
      {
        title: '共享单位类型',
        dataIndex: 'out_gxdw',
        render: (text, record) => (
          <Select defaultValue={text}
          style={{ width: "100%" }}
          onChange={value => this.setState({out_gxdw: value})}
          tokenSeparators={[","]}
          showArrow={true}
        >
          <Option value="BSHI">本室</Option>
          <Option value="BSUO">本所</Option>
          <Option value="WDW">外单位</Option>
          <Option value="QT">其他</Option>
        </Select>
              )
      },

      {
        title: '筛选菌株保藏方式',
        dataIndex: 'jzbc_type',
        render: (text, record) => (
          <Select defaultValue={text}
          //mode="tags"
          style={{ width: "100%" }}
          onChange={value => this.setState({jzbc_type : value[0]}) }
          tokenSeparators={','}
          showArrow={true}
        >
          <Option value="YD">液氮超低温冻结法</Option>
          <Option value="FB">－80摄氏度冰箱冻结法</Option>
          <Option value="ZK">真空冷冻干燥法</Option>
          <Option value="KW">矿物油法</Option>
          <Option value="YZ">定期移植法</Option>
          <Option value="QT">其他</Option>
        </Select>
              )
      },      
      {
        title: '共享课题组名称',
        dataIndex: 'out_group',
        editable: true,
      },
      {
        title: '筛选菌株用途',
        dataIndex: 'out_sxjzyt',
        editable: true,
      },
      {
        title: '批号',
        dataIndex: 'out_ph',
        editable: true,
      },
      {
        title: '出库数量',
        dataIndex: 'out_number',
        editable: true,
      },
      {
        title: '存放位置',
        dataIndex: 'store_place',
        editable: true,
      },
      {
        title: '存活情况',
        dataIndex: 'out_ch',
        render: (text, record) => (
          <Select defaultValue={text}
          //mode="tags"
          style={{ width: "100%" }}
          onChange={value => this.setState({out_ch: value[0]})}
          tokenSeparators={[","]}
          showArrow={true}
        >
            <Option value="Y">是</Option>
            <Option value="N">否</Option>

          </Select>
              )
      },
      {
        title: '纯度情况',
        dataIndex: 'out_cd',
        render: (text, record) => (
          <Select defaultValue={text}
         // mode="tags"
          style={{ width: "100%" }}
          onChange={value => this.setState({out_cd: value[0]})}
          tokenSeparators={[","]}
          showArrow={true}
        >
            <Option value="Y">是</Option>
            <Option value="N">否</Option>

          </Select>
              )
      },
      {
        title: '出库人',
        dataIndex: 'worker',
        editable: true,
      },
      {
        title: '出库时间',
        dataIndex: 'out_time',
        editable: true,
      },
      {
        title: '出库人联系方式',
        dataIndex: 'out_lxfs',
        editable: true,
      },
      {
        title: '使用人',
        dataIndex: 'user',
        editable: true,
      },
      {
        title: '使用时间',
        dataIndex: 'user_time',
        editable: true,
      },
      {
        title: '使用人联系方式',
        dataIndex: 'user_tel',
        editable: true,
      },
      {
        title: '备注',
        dataIndex: 'remark',
        editable: true,
      },
      
      {
        title: '编辑',
        dataIndex: 'operation',
        fixed: 'right',
        width:100,
        render: (text, record) => {

          const { editingKey } = this.state;
          const editable = this.isEditing(record);
          return editable ? (
            <span>
              <EditableContext.Consumer>
                {form => (
                  <a
                    onClick={() => this.update(form, record.id)}
                    style={{ marginRight: 8 }}
                  >
                    保存
                  </a>
                )}
              </EditableContext.Consumer>
              <Popconfirm title="Sure to cancel?" onConfirm={() => this.cancel(record.id)}>
                <a>取消</a>
              </Popconfirm>
            </span>
          ) : (
            <a disabled={editingKey !== ''} onClick={() => this.edit(record)}>
              编辑
            </a>
          );
        },
      },
      {
        title: '操作',
        dataIndex: 'address',
        fixed: 'right',
        width:200,
        render: (text, record) => (
          <span>
            <Button type="dashed"  onClick={() => this.setModalViewDetailVisible(true, record)}>
              查看
            </Button>
          </span>
        )
      },
    ];
    this.columns_yichuku = [
      {
        title: 'ID',
        dataIndex: 'id',
        editable: false,
        fixed: 'left',
        width:120,
      },      
      {
        title: '筛选菌株编号',
        dataIndex: 'sxjj_id',
        editable: true,
        fixed: 'left',
        width:200,
      },  
      {
        title: '菌株保藏编号',
        dataIndex: 'jzbc_id',
        editable: true,
        fixed: 'left',
        width:200,
      },
      {
        title: '共享单位类型',
        dataIndex: 'out_gxdw',
        render: () => (
          <Select
          //mode="tags"
          style={{ width: "100%" }}
          tokenSeparators={[","]}
          showArrow={true}
        >
          <Option value="jack">本室</Option>
          <Option value="lucy">本所</Option>
          <Option value="zhenleng">外单位</Option>
          <Option value="lucyq">其他</Option>
        </Select>
              )
      },
      {
        title: '共享课题组名称',
        dataIndex: 'out_group',
        editable: true,
      },
      {
        title: '筛选菌株用途',
        dataIndex: 'out_sxjzyt',
        editable: true,
      },
      {
        title: '批号',
        dataIndex: 'out_ph',
        editable: true,
      },
      {
        title: '出库数量',
        dataIndex: 'out_number',
        editable: true,
      },
      {
        title: '存放位置',
        dataIndex: 'store_place',
        editable: true,
      },
      {
        title: '存活情况',
        dataIndex: 'out_ch',
        render: () => (
          <InputGroup compact style={{ width: "100%" }}>
          <Select defaultValue="">
            <Option value="passage">是</Option>
            <Option value="methane">否</Option>

          </Select>
        </InputGroup>
              )
      },
      {
        title: '纯度情况',
        dataIndex: 'out_cd',
        render: () => (
          <InputGroup compact style={{ width: "100%" }}>
          <Select defaultValue="">
            <Option value="passage">是</Option>
            <Option value="methane">否</Option>

          </Select>
        </InputGroup>
              )
      },
      {
        title: '出库人',
        dataIndex: 'worker',
        editable: true,
      },
      {
        title: '出库时间',
        dataIndex: 'out_time',
        editable: true,
      },
      {
        title: '出库人联系方式',
        dataIndex: 'out_lxfs',
        editable: true,
      },
      {
        title: '使用人',
        dataIndex: 'user',
        editable: true,
      },
      {
        title: '使用时间',
        dataIndex: 'user_time',
        editable: true,
      },
      {
        title: '使用人联系方式',
        dataIndex: 'user_tel',
        editable: true,
      },
      {
        title: '备注',
        dataIndex: 'remark',
        editable: true,
      },
        
    ];

    
    this.state = { 
      dataSource: [], 
      count: 0,

      dataSource_yichuku: [],
      count_yichuku: 0,

      editingKey: '' ,     
      selectedRowKeys: [], // Check here to configure the default column

      keyword: '',
      newData: {},

      out_gxdw:'',
      out_cd:'',
      out_ch:'',

      loading: false,
      modalYichukuVisible: false,
      modalViewDetailVisible: false,
      viewRecord: {}
    };
    
  }


  // 显示已出库
  setModalYichukuVisible() {
    
    // 先调用接口获取数据，成功后显示Modal
    const url = global.api.ScreeningLibraryOut222;
    return global.getdata.get(url, {page_index: 1, page_size: this.state.pageSize,})
    .then(res => {
      this.setState({modalYichukuVisible: true, dataSource_yichuku: res.results, count_yichuku: res.count})
    })
    .catch(err => {
      Modal.error({
        content: '数据获取失败！'
      })
    })

  }

  setModalViewDetailVisible(visible, record = {}) {
    this.setState({ modalViewDetailVisible: visible, viewRecord: record });
  }

  isEditing = record => record.id === this.state.editingKey;

  cancel = () => {
    this.setState({ editingKey: '' });
  };

  update(form, id) {
    form.validateFields((error, row) => {
      if (error) {
        return;
      }

      let record = row;
    
      record.out_gxdw = this.state.out_gxdw;
      record.out_cd = this.state.out_cd;
      record.out_ch = this.state.out_ch;
      record.jzbc_type = this.state.jzbc_type;

      // 保存数据
      const url = global.api.screeningLibraryOut + id + '/';
      return global.updatedata.put(url, record)
      .then(res => {
        this.loadData(1);

        Modal.success({
          content: '保存成功！'
        })
      })
      .catch(err => {
        Modal.error({
          content: 'Err: 保存失败！'
        })
      }) 

    });

    // 保存数据

  }

  save(form, id) {
    form.validateFields((error, row) => {
      if (error) {
        return;
      }

      // 保存数据
      const url = global.api.screeningLibraryOut;
      return global.network.post(url, row)
      .then(res => {
        const newData = [...this.state.dataSource];
        const index = newData.findIndex(item => id === item.id);
        if (index > -1) {
          const item = newData[index];
          newData.splice(index, 1, {
            ...item,
            ...row,
          });
          this.setState({ dataSource: newData, editingKey: '' });
        } else {
          newData.push(row);
          this.setState({ dataSource: newData, editingKey: '' });
        }        

        Modal.success({
          content: '保存成功！'
        })
      })
      .catch(err => {
        Modal.error({
          content: 'Err: 保存失败！'
        })
      }) 

    });

    // 保存数据

  }

  edit(record) {
    this.setState({ 
      editingKey: record.id, 
      out_gxdw: record.out_gxdw,
      out_cd: record.out_cd,
      out_ch: record.out_ch,
      jzbc_type: record.jzbc_type 
    });
  }

  start = () => {
    this.setState({ loading: true });
    // ajax request after empty completing
    setTimeout(() => {
      this.setState({
        selectedRowKeys: [],
        loading: false,
      });
    }, 1000);
  };

  onSelectChange = selectedRowKeys => {
    console.log('selectedRowKeys changed: ', selectedRowKeys);
    this.setState({ selectedRowKeys });
  };

  loadData = (current = 1) => {

    this.setState({ loading: true });
    // ajax request after empty completing
    setTimeout(() => {
      this.setState({
        selectedRowKeys: [],
        loading: false
      });
    }, 1000);

    const url = global.api.screeningLibraryOut;
    return global.getdata.get(url, {page_index: current, page_size: this.state.pageSize, search: this.state.keyword})
    .then(res => {
      this.setState({dataSource: res.results, count: res.count})
    })
    .catch(err => {
      
    }) 

  }

  componentDidMount() {
    this.loadData(1);
  }

  // 导出入库单
  doOutput = () => {
    let selectedRowKeys = this.state.selectedRowKeys;
    if(selectedRowKeys) {
      for( let x of selectedRowKeys ) {
        let record = this.state.dataSource[x];
        let id = record.id;
        // TODO 跳转到导出URL
      }
    }   
  }
  // 出库
  doChuku = () => {
     let selectedRowKeys = this.state.selectedRowKeys;
     if(selectedRowKeys) {
       for( let x of selectedRowKeys ) {
         let record = this.state.dataSource[x];
         record.chuli_tag = 'ycl';

         const url = global.api.huijiaoinfo + record.id + '/';
         return global.updatedata.put(url, record)
     
         .then(res => {  
     
           const newData = [...this.state.dataSource];
           const index = newData.findIndex(item => item.id === record.id);
           const item = newData[index];
           newData.splice(index, 1, {
             ...item,
             ...record,
           });
           this.setState({ dataSource: newData });
     
           Modal.success({
             content: '出库成功!',
           });
         })
         .catch(err => {           
           Modal.error({
             content: '出库出错!',
           });
         }) 

       }
     }
  }

  handleAdd = () => {
    const { count, dataSource } = this.state;
    const initVal = count + 1;

    if( this.state.newData.id != null ) {
      Modal.error({
        content: '数据尚未保存！',
      });
      return;
    }
    const newData = {
      id: initVal,
      sxjj_id: initVal,
      jzbc_id : initVal,
      out_gxdw  : initVal,
      out_group  : initVal,

      out_sxjzyt  : initVal,
      out_ph  : initVal,
      out_number  : initVal,

      user_time: moment(new Date(), 'YYYY-MM-DD HH:mm:ss').format('YYYY-MM-DD HH:mm:ss'),
      out_time: moment(new Date(), 'YYYY-MM-DD HH:mm:ss').format('YYYY-MM-DD HH:mm:ss'),
      store_place: initVal,
      out_ch : '',
      out_cd : '',
      worker: initVal,
      out_lxfs : initVal,
      user : initVal,
      user_tel: initVal,
      remark: initVal
    };

    this.setState({
      dataSource: [...dataSource, newData],
      count: count + 1,
      newData: newData
    });
  };

  handleSave = (row, showAlert) => {
   
    let dataSource = [...this.state.dataSource];
    let record = null;
    if( row.id != null ) {
      record = row;
    } else {
      record = dataSource[dataSource.length - 1];
    }
    
    record.out_gxdw = this.state.out_gxdw;
    record.out_cd = this.state.out_cd;
    record.out_ch = this.state.out_ch;
    record.jzbc_type = this.state.jzbc_type;

    const url = global.api.screeningLibraryOut;
    return global.network.post(url, record)
    .then(res => {  
      this.loadData(1);

      if( showAlert ) {
        Modal.success({
          content: '保存成功!',
        });
      }

      this.setState({newData: {}})

    })
    .catch(err => {
      if( showAlert ) {
        Modal.error({
          content: '保存出错，请检查传入的参数是否已经填写！',
        });
      }
    }) 

  };

  render() {
  
    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 10 }
      }
    };
    const components = {
      body: {
        row: EditableFormRow,
        cell: EditableCell,
      },
    };
    const { loading, selectedRowKeys } = this.state;
    const rowSelection = {
      selectedRowKeys,
      onChange: this.onSelectChange,
    };
    const hasSelected = selectedRowKeys.length > 0;
    const columns = this.columns.map(col => {
      if (!col.editable) {
        return col;
      }
      return {
        ...col,
        onCell: record => ({
          record,
          inputType: col.dataIndex === 'age' ? 'number' : 'text',
          dataIndex: col.dataIndex,
          title: col.title,
          editing: this.isEditing(record),
        }),
      };
    });
    const columns_yichuku = this.columns_yichuku.map(col => {
      if (!col.editable) {
        return col;
      }
      return {
        ...col,
        onCell: record => ({
          record,
          inputType: col.dataIndex === 'age' ? 'number' : 'text',
          dataIndex: col.dataIndex,
          title: col.title,
          editing: this.isEditing(record),
        }),
      };
    });
    
    return (
      <Content>
         <div className="filtrate">
          <p style={{marginLeft:'100px'}}>
          <span className="span">
         <Input placeholder="输入查询内容" style={{ width: 500 }} onChange={value => this.setState({keyword: value})} />
          </span>
          <span className="span" >
            <Button loading={this.state.loading} type="primary" style={{ width: 80 }} onClick={() => this.loadData(1)}>
              查询
            </Button>
          </span>
          </p>
        </div>
        <Button
          type="primary"
          onClick={this.start}
          disabled={!hasSelected}
          loading={loading}
          style={{marginLeft:20,marginTop:20}}
          onClick={() => this.doOutput()}
        >
          导出
        </Button>
        <Button type="primary" style={{ marginLeft:20, display: 'none' }}>
              保存
        </Button>
        <Button type="primary" style={{ marginLeft:20 }} onClick={this.doChuku}>
              出库
        </Button>
        <Button type="primary" style={{ marginLeft:20 }}
          onClick={() => this.setModalYichukuVisible()}
        >
              已出库
        </Button>
        <span style={{ marginLeft: 8 }}>
          {hasSelected ? `选中 ${selectedRowKeys.length} 个` : ""}
        </span>
        <Modal
          title="20px to Top"
          style={{ top: 20 }}
          visible={this.state.modalYichukuVisible}
          onOk={() => this.setState({modalYichukuVisible: false})}
          onCancel={() => this.setState({modalYichukuVisible: false})}
        >
          <Table
          rowSelection={rowSelection}
          components={components}
          bordered
          columns={columns_yichuku}
          dataSource={this.state.dataSource_yichuku}
          rowClassName="editable-row"
          pagination={{
            onChange: this.cancel,
          }}
          scroll={{ x: 3100}}
        />
        </Modal>
        <Modal
          title="基本信息"
          visible={this.state.modalViewDetailVisible}
          onOk={() => this.setModalViewDetailVisible(false, {})}
          onCancel={() => this.setModalViewDetailVisible(false, {})}
        >
        <Form {...formItemLayout} onSubmit={this.onSubmit} colon={false}>
          <div style={{display:'flex'}}>
          <span style={{flex:'1'}}>
            <Item label="ID"><Input defaultValue={this.state.viewRecord.id } /></Item>
            <Item label="筛选菌株编号"><Input defaultValue={this.state.viewRecord.sxjj_id } /></Item>
            <Item label="菌株保藏编号"><Input defaultValue={this.state.viewRecord.jzbc_id } /></Item>
            <Item label="共享单位类型"><Input defaultValue={this.state.viewRecord.out_gxdw } /></Item>
            <Item label="共享课题组名称"><Input defaultValue={this.state.viewRecord.out_group } /></Item>
            <Item label="筛选菌株用途"><Input defaultValue={this.state.viewRecord.out_sxjzyt } /></Item>
            <Item label="批号"><Input defaultValue={this.state.viewRecord.out_ph } /></Item>
            <Item label="出库数量"><Input defaultValue={this.state.viewRecord.out_number } /></Item>
            <Item label="存放位置"><Input defaultValue={this.state.viewRecord.store_place } /></Item>
          </span>
          <span style={{flex:'1'}}>
            <Item label="存活情况"><Input defaultValue={this.state.viewRecord.out_ch } /></Item>
            <Item label="纯度情况"><Input defaultValue={this.state.viewRecord.out_cd } /></Item>
            <Item label="出库人"><Input defaultValue={this.state.viewRecord.worker } /></Item>
            <Item label="出库时间"><Input defaultValue={this.state.viewRecord.out_time } /></Item>
            <Item label="出库人联系方式"><Input defaultValue={this.state.viewRecord.out_lxfs } /></Item>
            <Item label="使用人"><Input defaultValue={this.state.viewRecord.user } /></Item>
            <Item label="使用时间"><Input defaultValue={this.state.viewRecord.user_time } /></Item>
            <Item label="使用人联系方式"><Input defaultValue={this.state.viewRecord.user_tel } /></Item>
            <Item label="备注说明"><Input defaultValue={this.state.viewRecord.remark } /></Item>
            
            <Item wrapperCol={{ span: 12, offset: 4 }} style={{display: 'none'}}>
              <Row guuter={16}>
                <Col span={6}>
                  <Button type="primary" htmlType="submit">
                    确定
                  </Button>
                </Col>
              </Row>
            </Item>
          </span>
        </div>
      </Form>
        </Modal>
      <EditableContext.Provider value={this.props.form}>
        <Table
          rowSelection={rowSelection}
          components={components}
          bordered
          dataSource={this.state.dataSource}
          columns={columns}
          rowClassName="editable-row"
          pagination={{
            onChange: this.cancel,
          }}
          scroll={{ x: 3100}}
        />


        <div style={{marginLeft: 16}}>  
          <Button onClick={this.handleAdd} type="primary" >
            添加
          </Button>
          <Button disabled={this.state.newData.id == null} onClick={(record) => this.handleSave(record, true)}  type="primary" style={{ marginLeft: 16 }}>
            保存
          </Button>
        </div>        
      </EditableContext.Provider>

      </Content>
    );
  }
}

const CompoundInfo = Form.create()(EditableTable);

export default CompoundInfo;
